package com.hm.system.web;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.hm.common.annotation.AuthenticationAnnotation;
import com.hm.common.annotation.RequestPlanAnnotation;
import com.hm.common.common.EncryptUtil.Md5;
import com.hm.common.common.VerifyCodeUtil;
import com.hm.common.model.ControllerResult;
import com.hm.common.model.LoginUserInfo;
import com.hm.common.util.CommonDef;
import com.hm.system.auto.SystemProperties;
import com.hm.system.mongo.vo.system.SysUserInfoVo;
import com.hm.system.share.service.mongo.system.SysUserInfoService;
import com.hm.system.util.SystemConfigDef.Api.Rest;
import com.hm.system.util.SystemConfigDef.BaseInit.SessionOrCookieToken;
import com.hm.system.web.su.BaseController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@ResponseBody
@RestController
@RequestMapping(value = Rest.Sys.REST_ENTRANCE)
public class EntranceController extends BaseController{

	public static final String swaggerTag = "登录-用户权限";
	
	@Autowired
	private SystemProperties systemProperties;

	@Autowired
	private SysUserInfoService sysUserInfoService;
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ApiOperation(value = "系统用户登录-正式环境", httpMethod = "POST", notes = "系统用户登录", tags = swaggerTag)
	@RequestPlanAnnotation(title = "系统用户登录-正式环境", content = "系统用户登录")
	public ResponseEntity<ControllerResult<String>> login(
			@ApiParam(required = true, name = "name", value = "名称") @RequestParam("name") String name,
			@ApiParam(required = true, name = "pwd", value = "密码") @RequestParam("pwd") String pwd,
			HttpSession session) {
		try {
			SysUserInfoVo sysUserInfoVo = sysUserInfoService.checkSysUserInfo(name, pwd);
			if (null != sysUserInfoVo) {
				LoginUserInfo loginUserInfo = new LoginUserInfo();
				{
					loginUserInfo.setId(sysUserInfoVo.getId());
					loginUserInfo.setName(sysUserInfoVo.getName());
				}
				
				session.setAttribute(CommonDef.BaseInit.SessionOrCookieToken.SESSION_LOGIN_USER_INFO, loginUserInfo);
				return ControllerResult.success(sysUserInfoVo.getId(), "登陆成功");
			}
			return ControllerResult.failed("登陆失败");
		} catch (Exception e) {
			return ControllerResult.failed(e.getMessage());
		}
	}

	@RequestMapping(value = "/loginTest", method = RequestMethod.DELETE)
	@ApiOperation(value = "系统用户登录-测试环境", httpMethod = "DELETE", notes = "系统用户登录--测试开发环境调试用,正式环境应该屏蔽掉", tags = swaggerTag)
	@RequestPlanAnnotation(title = "系统用户登录-测试环境", content = "系统用户登录--测试开发环境调试用,正式环境应该屏蔽掉")
	public ResponseEntity<ControllerResult<String>> loginTest(
			@ApiParam(required = true, name = "name", value = "名称", defaultValue = "admin") @RequestParam("name") String name,
			@ApiParam(required = true, name = "pwd", value = "密码", defaultValue = "password") @RequestParam("pwd") String pwd,
			HttpSession session) {
		return login(name, pwd, session);
	}

	@RequestMapping(value = "/init/{authorization}", method = RequestMethod.PUT)
	@ApiOperation(value = "初始化系统数据", httpMethod = "PUT", notes = "初始化系统数据", tags = swaggerTag)
	@RequestPlanAnnotation(title = "初始化系统数据", content = "初始化系统数据")
	public ResponseEntity<ControllerResult<String>> initSystemData(
			@ApiParam(required = true, name = "authorization", value = "注册码") @PathVariable String authorization) {
		try {
			if(authorization.equals(systemProperties.getSystemInit().getAuthorization())){
				//删除历史数据
				sysUserInfoService.removeAll();
				//重新初始化数据
				sysUserInfoService.initUserInfo();
				return ControllerResult.success("初始化成功");
			}
			return ControllerResult.failed("注册码不争取,系统初始化失败");
		} catch (Exception e) {
			return ControllerResult.failed(e.getMessage());
		}
	}
	
	@AuthenticationAnnotation
	@RequestMapping(value = "/token/{clientTime}", method = RequestMethod.GET)
	@ApiOperation(value = "申请数据操作Token", httpMethod = "GET", notes = "每次数据要提交之前申请Token验证,防止表单提交,同时也防止表单注入", tags = swaggerTag)
	@RequestPlanAnnotation(title = "申请数据操作Token", content = "每次数据要提交之前申请Token验证,防止表单提交,同时也防止表单注入")
	public ResponseEntity<ControllerResult<String>> generationToken(
			@ApiParam(required = true, name = "clientTime", value = "时间戳") @PathVariable Long clientTime,
			HttpServletRequest request){
		try {
			String token = Md5.getMD5Code(UUID.randomUUID().toString()+clientTime);
			request.getSession().setAttribute(SessionOrCookieToken.REQUEST_TOKEN, token);
			return ControllerResult.success(token);
		} catch (Exception e) {
			return ControllerResult.failed(e.getMessage());
		}
	}

	@RequestMapping(value = "/verifycode/{clientTime}.jpg", method = RequestMethod.GET)
	@ApiOperation(value = "获取随机验证码", httpMethod = "GET", notes = "获取随机验证码", tags = swaggerTag)
	public void verifyCode(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(required = true, name = "width", value = "验证码长度") @RequestParam("width") int width,
			@ApiParam(required = true, name = "height", value = "验证码高度") @RequestParam("height") int height,
			@ApiParam(required = true, name = "size", value = "随机数长度") @RequestParam("size") int size,
			@ApiParam(required = true, name = "clientTime", value = "时间戳") @PathVariable Long clientTime)
					throws Exception {
		{// 设置请求响应头
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpeg");
		}
		String code = VerifyCodeUtil.generateVerifyCode(size);
		VerifyCodeUtil.outputImage(width, height, response.getOutputStream(), code);
	}
}
